﻿using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Linq;
using System.Security.Claims;
using System.Text;

namespace CommonDevelop.Operator
{
    public sealed class JwtHelper
    {
        private const string SecretKey = "726774b9dac3484cbf70e584ca30720a";    //安全Key
        public static readonly SymmetricSecurityKey signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SecretKey));

        /// <summary>
        /// 生成签名凭据
        /// </summary>
        public static SigningCredentials GenerateSigningCredentials()
            => new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);

        public static string GetToken()
        {
            try
            {
                var httpContextAccessor = IocContainer.Resolve<IHttpContextAccessor>();
                var claimsIdentity = httpContextAccessor.HttpContext.User.Identity as ClaimsIdentity;
                var userId = claimsIdentity?.Claims.SingleOrDefault(m => m.Type == ClaimTypes.SerialNumber);
                return userId?.Value;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public static string GetUserID()
        {
            try
            {
                var httpContextAccessor = IocContainer.Resolve<IHttpContextAccessor>();
                var claimsIdentity = httpContextAccessor.HttpContext.User.Identity as ClaimsIdentity;
                var userId = claimsIdentity?.Claims.SingleOrDefault(m => m.Type == ClaimTypes.UserData);
                return userId?.Value;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public static string GetBusinessID()
        {
            try
            {
                var httpContextAccessor = IocContainer.Resolve<IHttpContextAccessor>();
                var claimsIdentity = httpContextAccessor.HttpContext.User.Identity as ClaimsIdentity;
                var claimBid = claimsIdentity?.Claims.SingleOrDefault(m => m.Type == ClaimTypes.GroupSid);
                return claimBid?.Value;
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 获取HttpContext
        /// </summary>
        public static HttpContext GetHttpContext()
        {
            var httpContextAccessor = IocContainer.Resolve<IHttpContextAccessor>();
            return httpContextAccessor?.HttpContext;
        }
    }
}
